package ntd.util;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.thread.lock.LockUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.StaticLog;
import ntd.util.fun.ComFun;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.StampedLock;

/**
 * 锁执行
 */
public class ToolLock {

    private static final Cache<String, StampedLock> LOCK_LFU_CACHE = CacheUtil.newLRUCache(10000);

    private static final ConcurrentHashMap<String, ConcurrentLinkedQueue<ComFun.Fun>> concurrentHashMap = new ConcurrentHashMap();

    private static int num = 0;

    private synchronized static StampedLock initLock(String key) {
        StampedLock stampedLock = LOCK_LFU_CACHE.get(key);
        if (ObjectUtil.isNull(stampedLock)) {
            LOCK_LFU_CACHE.put(key, stampedLock = LockUtil.createStampLock());
//            StaticLog.info("创建锁[{}][{}]", key, num++);
        }
        return stampedLock;
    }

    /**
     * 悲观锁运行
     *
     * @param key
     * @param fun
     */
    public static void lockRun(String key, ComFun.Fun fun) {
        StampedLock stampedLock = initLock(key);
        // 获取悲观锁
        long stamp = stampedLock.writeLock();
        try {
            fun.accept();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            // 释放悲观锁
            stampedLock.unlockWrite(stamp);
        }
    }

    public static void main(String[] args) {
        AtomicReference<Integer> reference1 = new AtomicReference<>(0);
        AtomicReference<Integer> reference2 = new AtomicReference<>(0);
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            ThreadUtil.execAsync(() -> {
                int i1 = finalI % 2;
                lockRun("test" + i1, () -> {
                    ThreadUtil.sleep(50);
                    if (i1 == 0) {
                        reference1.set(reference1.get() + finalI);
                    }
                    if (i1 == 1) {
                        reference2.set(reference2.get() + finalI);
                    }
                });
                StaticLog.info("锁定测试结果1[{}]", reference1.get());
                StaticLog.info("锁定测试结果2[{}]", reference2.get());
            });
        }

    }
}
